<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { OnActionClickParams, VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { Button, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteTender,
  getRegionTree,
  getTags,
  getTenderList,
  getTenderTypes,
} from '#/api';
import { tagType } from '#/utils/bid';

import Form from './modules/form.vue';
import ImportForm from './modules/import.vue';

const gridOptions: VxeGridProps<App.Http.Resources.TenderItem> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    {
      field: 'regions',
      slots: { default: 'regions' },
      title: '地区',
      align: 'left',
      width: 180,
    },
    {
      field: 'title',
      title: '标题',
      minWidth: 200,
      showOverflow: 'tooltip',
      align: 'left',
    },
    {
      field: 'type.name',
      title: '状态',
      width: 100,
    },
    {
      title: '项目类型',
      field: 'project_type',
      minWidth: 150,
      maxWidth: 300,
      slots: { default: 'project_type' },
    },
    {
      title: '标签',
      field: 'tags',
      minWidth: 150,
      maxWidth: 300,
      slots: { default: 'tags' },
    },
    {
      field: 'publish_date',
      formatter: 'formatDate',
      title: '发布日期',
      width: 150,
    },
    {
      title: '关联项目',
      field: 'project_id',
    },
    {
      cellRender: {
        attrs: {
          nameField: 'title',
          onClick: onAction,
        },
        name: 'CellOperation',
        options: [
          'edit', // 默认的编辑按钮
          'delete', // 默认的删除按钮
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 120,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        console.warn(formValues);
        return await getTenderList({
          page: {
            number: page.currentPage,
            size: page.pageSize,
          },
        });
      },
    },
  },
  showOverflow: false,
};

const formOptions: VbenFormProps = {
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        api: () => getTags('project_type'),
        labelField: 'name',
        valueField: 'id',
        clearable: true,
      },
      fieldName: 'tag_project_type',
      label: '项目类型',
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        api: () => getRegionTree(),
        class: 'w-full',
        filterable: true,
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        clearable: true,
      },
      fieldName: 'region_id',
      label: '区域',
    },
    {
      component: 'ApiSelect',
      componentProps: {
        api: () => getTenderTypes(),
        labelField: 'name',
        valueField: 'id',
        clearable: true,
      },
      fieldName: 'type_id',
      label: '招标状态',
    },
    {
      component: 'RangePicker',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
      defaultValue: [dayjs().subtract(7, 'days'), dayjs()],
      fieldName: 'publish_date',
      label: '发布时间',
    },
    {
      component: 'ApiSelect',
      componentProps: {
        api: () => getTags('project'),
        labelField: 'name',
        valueField: 'id',
        mode: 'multiple',
      },
      fieldName: 'tag_project',
      label: '标签',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });

const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: ImportForm,
  destroyOnClose: true,
});

function onImport() {
  console.warn('onImport');
  importModalApi.setData({ file: [] }).open();
}

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

async function onEdit(row: App.Http.Resources.TenderItem) {
  const rowData = {
    ...row,
    type_id: row.type.id,
    region_id: row.regions[row.regions.length - 1]?.id,
    tag: {
      project_type: row.tag.project_type?.map((tag) => tag.id),
      project: row.tag.project?.map((tag) => tag.id),
    },
    url: row.url?.[0],
    agent_id: row.agent?.id,
    entity_id: row.entity?.id,
  };
  formDrawerApi.setData(rowData).open();
}
async function onDelete(row: App.Http.Resources.TenderItem) {
  await deleteTender(row.id);
  onRefresh();
}
function onAction({
  code,
  row,
}: OnActionClickParams<App.Http.Resources.TenderItem>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }

    default: {
      break;
    }
  }
}
function onCreate() {
  formDrawerApi.open();
}
function onRefresh() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <ImportModal />
    <FormDrawer @success="onRefresh" />
    <Grid>
      <template #toolbar-tools>
        <div class="flex gap-2">
          <Button type="primary" @click="onImport">
            <template #icon>
              <div class="i-lucide:import text-lg"></div>
            </template>
            导入
          </Button>
          <Button type="default" @click="onCreate">
            <template #icon>
              <div class="i-lucide:circle-plus text-lg"></div>
            </template>
            新增
          </Button>
        </div>
      </template>
      <template #regions="{ row }">
        {{
          row.regions
            .map((region) =>
              region.short_name ? region.short_name : region.name,
            )
            .join(' - ')
        }}
      </template>
      <template #project_type="{ row }">
        <div class="flex flex-wrap justify-center gap-2">
          <Tag
            :color="tagType(tag.id)"
            v-for="tag in row.tag.project_type"
            :key="tag.id"
          >
            {{ tag.name }}
          </Tag>
        </div>
      </template>
      <template #tags="{ row }">
        <div class="flex flex-wrap justify-center gap-2">
          <Tag
            :color="tagType(tag.id)"
            v-for="tag in row.tag.project"
            :key="tag.id"
          >
            {{ tag.name }}
          </Tag>
        </div>
      </template>
    </Grid>
  </Page>
</template>
